home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / ftplib.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2008-10-29  |  26.1 KB  |  991 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. """An FTP client class and some helper functions.
  5.  
  6. Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds
  7.  
  8. Example:
  9.  
  10. >>> from ftplib import FTP
  11. >>> ftp = FTP('ftp.python.org') # connect to host, default port
  12. >>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@
  13. '230 Guest login ok, access restrictions apply.'
  14. >>> ftp.retrlines('LIST') # list directory contents
  15. total 9
  16. drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
  17. drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
  18. drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
  19. drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
  20. d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
  21. drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
  22. drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
  23. drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
  24. -rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg
  25. '226 Transfer complete.'
  26. >>> ftp.quit()
  27. '221 Goodbye.'
  28. >>>
  29.  
  30. A nice test that reveals some of the network dialogue would be:
  31. python ftplib.py -d localhost -l -p -l
  32. """
  33. import os
  34. import sys
  35.  
  36. try:
  37.     import SOCKS
  38.     socket = SOCKS
  39.     del SOCKS
  40.     from socket import getfqdn
  41.     socket.getfqdn = getfqdn
  42.     del getfqdn
  43. except ImportError:
  44.     import socket
  45.  
  46. __all__ = [
  47.     'FTP',
  48.     'Netrc']
  49. MSG_OOB = 1
  50. FTP_PORT = 21
  51.  
  52. class Error(Exception):
  53.     pass
  54.  
  55.  
  56. class error_reply(Error):
  57.     pass
  58.  
  59.  
  60. class error_temp(Error):
  61.     pass
  62.  
  63.  
  64. class error_perm(Error):
  65.     pass
  66.  
  67.  
  68. class error_proto(Error):
  69.     pass
  70.  
  71. all_errors = (Error, socket.error, IOError, EOFError)
  72. CRLF = '\r\n'
  73.  
  74. class FTP:
  75.     """An FTP client class.
  76.  
  77.     To create a connection, call the class using these argument:
  78.             host, user, passwd, acct
  79.     These are all strings, and have default value ''.
  80.     Then use self.connect() with optional host and port argument.
  81.  
  82.     To download a file, use ftp.retrlines('RETR ' + filename),
  83.     or ftp.retrbinary() with slightly different arguments.
  84.     To upload a file, use ftp.storlines() or ftp.storbinary(),
  85.     which have an open file as argument (see their definitions
  86.     below for details).
  87.     The download/upload functions first issue appropriate TYPE
  88.     and PORT or PASV commands.
  89. """
  90.     debugging = 0
  91.     host = ''
  92.     port = FTP_PORT
  93.     sock = None
  94.     file = None
  95.     welcome = None
  96.     passiveserver = 1
  97.     
  98.     def __init__(self, host = '', user = '', passwd = '', acct = ''):
  99.         if host:
  100.             self.connect(host)
  101.             if user:
  102.                 self.login(user, passwd, acct)
  103.             
  104.         
  105.  
  106.     
  107.     def connect(self, host = '', port = 0):
  108.         '''Connect to host.  Arguments are:
  109.         - host: hostname to connect to (string, default previous host)
  110.         - port: port to connect to (integer, default previous port)'''
  111.         if host:
  112.             self.host = host
  113.         
  114.         if port:
  115.             self.port = port
  116.         
  117.         msg = 'getaddrinfo returns an empty list'
  118.         for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM):
  119.             (af, socktype, proto, canonname, sa) = res
  120.             
  121.             try:
  122.                 self.sock = socket.socket(af, socktype, proto)
  123.                 self.sock.connect(sa)
  124.             except socket.error:
  125.                 msg = None
  126.                 if self.sock:
  127.                     self.sock.close()
  128.                 
  129.                 self.sock = None
  130.                 continue
  131.  
  132.         
  133.         if not self.sock:
  134.             raise socket.error, msg
  135.         
  136.         self.af = af
  137.         self.file = self.sock.makefile('rb')
  138.         self.welcome = self.getresp()
  139.         return self.welcome
  140.  
  141.     
  142.     def getwelcome(self):
  143.         '''Get the welcome message from the server.
  144.         (this is read and squirreled away by connect())'''
  145.         if self.debugging:
  146.             print '*welcome*', self.sanitize(self.welcome)
  147.         
  148.         return self.welcome
  149.  
  150.     
  151.     def set_debuglevel(self, level):
  152.         '''Set the debugging level.
  153.         The required argument level means:
  154.         0: no debugging output (default)
  155.         1: print commands and responses but not body text etc.
  156.         2: also print raw lines read and sent before stripping CR/LF'''
  157.         self.debugging = level
  158.  
  159.     debug = set_debuglevel
  160.     
  161.     def set_pasv(self, val):
  162.         '''Use passive or active mode for data transfers.
  163.         With a false argument, use the normal PORT mode,
  164.         With a true argument, use the PASV command.'''
  165.         self.passiveserver = val
  166.  
  167.     
  168.     def sanitize(self, s):
  169.         if s[:5] == 'pass ' or s[:5] == 'PASS ':
  170.             i = len(s)
  171.             while i > 5 and s[i - 1] in '\r\n':
  172.                 i = i - 1
  173.             s = s[:5] + '*' * (i - 5) + s[i:]
  174.         
  175.         return repr(s)
  176.  
  177.     
  178.     def putline(self, line):
  179.         line = line + CRLF
  180.         if self.debugging > 1:
  181.             print '*put*', self.sanitize(line)
  182.         
  183.         self.sock.sendall(line)
  184.  
  185.     
  186.     def putcmd(self, line):
  187.         if self.debugging:
  188.             print '*cmd*', self.sanitize(line)
  189.         
  190.         self.putline(line)
  191.  
  192.     
  193.     def getline(self):
  194.         line = self.file.readline()
  195.         if self.debugging > 1:
  196.             print '*get*', self.sanitize(line)
  197.         
  198.         if not line:
  199.             raise EOFError
  200.         
  201.         if line[-2:] == CRLF:
  202.             line = line[:-2]
  203.         elif line[-1:] in CRLF:
  204.             line = line[:-1]
  205.         
  206.         return line
  207.  
  208.     
  209.     def getmultiline(self):
  210.         line = self.getline()
  211.         if line[3:4] == '-':
  212.             code = line[:3]
  213.             while None:
  214.                 nextline = self.getline()
  215.                 line = line + '\n' + nextline
  216.                 if nextline[:3] == code and nextline[3:4] != '-':
  217.                     break
  218.                     continue
  219.                 continue
  220.         line[3:4] == '-'
  221.         return line
  222.  
  223.     
  224.     def getresp(self):
  225.         resp = self.getmultiline()
  226.         if self.debugging:
  227.             print '*resp*', self.sanitize(resp)
  228.         
  229.         self.lastresp = resp[:3]
  230.         c = resp[:1]
  231.         if c in ('1', '2', '3'):
  232.             return resp
  233.         
  234.         if c == '4':
  235.             raise error_temp, resp
  236.         
  237.         if c == '5':
  238.             raise error_perm, resp
  239.         
  240.         raise error_proto, resp
  241.  
  242.     
  243.     def voidresp(self):
  244.         """Expect a response beginning with '2'."""
  245.         resp = self.getresp()
  246.         if resp[0] != '2':
  247.             raise error_reply, resp
  248.         
  249.         return resp
  250.  
  251.     
  252.     def abort(self):
  253.         """Abort a file transfer.  Uses out-of-band data.
  254.         This does not follow the procedure from the RFC to send Telnet
  255.         IP and Synch; that doesn't seem to work with the servers I've
  256.         tried.  Instead, just send the ABOR command as OOB data."""
  257.         line = 'ABOR' + CRLF
  258.         if self.debugging > 1:
  259.             print '*put urgent*', self.sanitize(line)
  260.         
  261.         self.sock.sendall(line, MSG_OOB)
  262.         resp = self.getmultiline()
  263.         if resp[:3] not in ('426', '226'):
  264.             raise error_proto, resp
  265.         
  266.  
  267.     
  268.     def sendcmd(self, cmd):
  269.         '''Send a command and return the response.'''
  270.         self.putcmd(cmd)
  271.         return self.getresp()
  272.  
  273.     
  274.     def voidcmd(self, cmd):
  275.         """Send a command and expect a response beginning with '2'."""
  276.         self.putcmd(cmd)
  277.         return self.voidresp()
  278.  
  279.     
  280.     def sendport(self, host, port):
  281.         '''Send a PORT command with the current host and the given
  282.         port number.
  283.         '''
  284.         hbytes = host.split('.')
  285.         pbytes = [
  286.             repr(port / 256),
  287.             repr(port % 256)]
  288.         bytes = hbytes + pbytes
  289.         cmd = 'PORT ' + ','.join(bytes)
  290.         return self.voidcmd(cmd)
  291.  
  292.     
  293.     def sendeprt(self, host, port):
  294.         '''Send a EPRT command with the current host and the given port number.'''
  295.         af = 0
  296.         if self.af == socket.AF_INET:
  297.             af = 1
  298.         
  299.         if self.af == socket.AF_INET6:
  300.             af = 2
  301.         
  302.         if af == 0:
  303.             raise error_proto, 'unsupported address family'
  304.         
  305.         fields = [
  306.             '',
  307.             repr(af),
  308.             host,
  309.             repr(port),
  310.             '']
  311.         cmd = 'EPRT ' + '|'.join(fields)
  312.         return self.voidcmd(cmd)
  313.  
  314.     
  315.     def makeport(self):
  316.         '''Create a new socket and send a PORT command for it.'''
  317.         msg = 'getaddrinfo returns an empty list'
  318.         sock = None
  319.         for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
  320.             (af, socktype, proto, canonname, sa) = res
  321.             
  322.             try:
  323.                 sock = socket.socket(af, socktype, proto)
  324.                 sock.bind(sa)
  325.             except socket.error:
  326.                 msg = None
  327.                 if sock:
  328.                     sock.close()
  329.                 
  330.                 sock = None
  331.                 continue
  332.  
  333.         
  334.         if not sock:
  335.             raise socket.error, msg
  336.         
  337.         sock.listen(1)
  338.         port = sock.getsockname()[1]
  339.         host = self.sock.getsockname()[0]
  340.         if self.af == socket.AF_INET:
  341.             resp = self.sendport(host, port)
  342.         else:
  343.             resp = self.sendeprt(host, port)
  344.         return sock
  345.  
  346.     
  347.     def makepasv(self):
  348.         if self.af == socket.AF_INET:
  349.             (host, port) = parse227(self.sendcmd('PASV'))
  350.         else:
  351.             (host, port) = parse229(self.sendcmd('EPSV'), self.sock.getpeername())
  352.         return (host, port)
  353.  
  354.     
  355.     def ntransfercmd(self, cmd, rest = None):
  356.         """Initiate a transfer over the data connection.
  357.  
  358.         If the transfer is active, send a port command and the
  359.         transfer command, and accept the connection.  If the server is
  360.         passive, send a pasv command, connect to it, and start the
  361.         transfer command.  Either way, return the socket for the
  362.         connection and the expected size of the transfer.  The
  363.         expected size may be None if it could not be determined.
  364.  
  365.         Optional `rest' argument can be a string that is sent as the
  366.         argument to a RESTART command.  This is essentially a server
  367.         marker used to tell the server to skip over any data up to the
  368.         given marker.
  369.         """
  370.         size = None
  371.         if self.passiveserver:
  372.             (host, port) = self.makepasv()
  373.             (af, socktype, proto, canon, sa) = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0]
  374.             conn = socket.socket(af, socktype, proto)
  375.             conn.connect(sa)
  376.             if rest is not None:
  377.                 self.sendcmd('REST %s' % rest)
  378.             
  379.             resp = self.sendcmd(cmd)
  380.             if resp[0] == '2':
  381.                 resp = self.getresp()
  382.             
  383.             if resp[0] != '1':
  384.                 raise error_reply, resp
  385.             
  386.         else:
  387.             sock = self.makeport()
  388.             if rest is not None:
  389.                 self.sendcmd('REST %s' % rest)
  390.             
  391.             resp = self.sendcmd(cmd)
  392.             if resp[0] == '2':
  393.                 resp = self.getresp()
  394.             
  395.             if resp[0] != '1':
  396.                 raise error_reply, resp
  397.             
  398.             (conn, sockaddr) = sock.accept()
  399.         if resp[:3] == '150':
  400.             size = parse150(resp)
  401.         
  402.         return (conn, size)
  403.  
  404.     
  405.     def transfercmd(self, cmd, rest = None):
  406.         '''Like ntransfercmd() but returns only the socket.'''
  407.         return self.ntransfercmd(cmd, rest)[0]
  408.  
  409.     
  410.     def login(self, user = '', passwd = '', acct = ''):
  411.         '''Login, default anonymous.'''
  412.         if not user:
  413.             user = 'anonymous'
  414.         
  415.         if not passwd:
  416.             passwd = ''
  417.         
  418.         if not acct:
  419.             acct = ''
  420.         
  421.         if user == 'anonymous' and passwd in ('', '-'):
  422.             passwd = passwd + 'anonymous@'
  423.         
  424.         resp = self.sendcmd('USER ' + user)
  425.         if resp[0] == '3':
  426.             resp = self.sendcmd('PASS ' + passwd)
  427.         
  428.         if resp[0] == '3':
  429.             resp = self.sendcmd('ACCT ' + acct)
  430.         
  431.         if resp[0] != '2':
  432.             raise error_reply, resp
  433.         
  434.         return resp
  435.  
  436.     
  437.     def retrbinary(self, cmd, callback, blocksize = 8192, rest = None):
  438.         """Retrieve data in binary mode.
  439.  
  440.         `cmd' is a RETR command.  `callback' is a callback function is
  441.         called for each block.  No more than `blocksize' number of
  442.         bytes will be read from the socket.  Optional `rest' is passed
  443.         to transfercmd().
  444.  
  445.         A new port is created for you.  Return the response code.
  446.         """
  447.         self.voidcmd('TYPE I')
  448.         conn = self.transfercmd(cmd, rest)
  449.         while None:
  450.             data = conn.recv(blocksize)
  451.             if not data:
  452.                 break
  453.             
  454.             continue
  455.             conn.close()
  456.             return self.voidresp()
  457.  
  458.     
  459.     def retrlines(self, cmd, callback = None):
  460.         '''Retrieve data in line mode.
  461.         The argument is a RETR or LIST command.
  462.         The callback function (2nd argument) is called for each line,
  463.         with trailing CRLF stripped.  This creates a new port for you.
  464.         print_line() is the default callback.'''
  465.         if callback is None:
  466.             callback = print_line
  467.         
  468.         resp = self.sendcmd('TYPE A')
  469.         conn = self.transfercmd(cmd)
  470.         fp = conn.makefile('rb')
  471.         while None:
  472.             line = fp.readline()
  473.             if self.debugging > 2:
  474.                 print '*retr*', repr(line)
  475.             
  476.             if not line:
  477.                 break
  478.             
  479.             if line[-2:] == CRLF:
  480.                 line = line[:-2]
  481.             elif line[-1:] == '\n':
  482.                 line = line[:-1]
  483.             
  484.             continue
  485.             fp.close()
  486.             conn.close()
  487.             return self.voidresp()
  488.  
  489.     
  490.     def storbinary(self, cmd, fp, blocksize = 8192):
  491.         '''Store a file in binary mode.'''
  492.         self.voidcmd('TYPE I')
  493.         conn = self.transfercmd(cmd)
  494.         while None:
  495.             buf = fp.read(blocksize)
  496.             if not buf:
  497.                 break
  498.             
  499.             continue
  500.             conn.close()
  501.             return self.voidresp()
  502.  
  503.     
  504.     def storlines(self, cmd, fp):
  505.         '''Store a file in line mode.'''
  506.         self.voidcmd('TYPE A')
  507.         conn = self.transfercmd(cmd)
  508.         while None:
  509.             buf = fp.readline()
  510.             if not buf:
  511.                 break
  512.             
  513.             if buf[-2:] != CRLF:
  514.                 if buf[-1] in CRLF:
  515.                     buf = buf[:-1]
  516.                 
  517.                 buf = buf + CRLF
  518.             
  519.             continue
  520.             conn.close()
  521.             return self.voidresp()
  522.  
  523.     
  524.     def acct(self, password):
  525.         '''Send new account name.'''
  526.         cmd = 'ACCT ' + password
  527.         return self.voidcmd(cmd)
  528.  
  529.     
  530.     def nlst(self, *args):
  531.         '''Return a list of files in a given directory (default the current).'''
  532.         cmd = 'NLST'
  533.         for arg in args:
  534.             cmd = cmd + ' ' + arg
  535.         
  536.         files = []
  537.         self.retrlines(cmd, files.append)
  538.         return files
  539.  
  540.     
  541.     def dir(self, *args):
  542.         '''List a directory in long form.
  543.         By default list current directory to stdout.
  544.         Optional last argument is callback function; all
  545.         non-empty arguments before it are concatenated to the
  546.         LIST command.  (This *should* only be used for a pathname.)'''
  547.         cmd = 'LIST'
  548.         func = None
  549.         if args[-1:] and type(args[-1]) != type(''):
  550.             args = args[:-1]
  551.             func = args[-1]
  552.         
  553.         for arg in args:
  554.             if arg:
  555.                 cmd = cmd + ' ' + arg
  556.                 continue
  557.         
  558.         self.retrlines(cmd, func)
  559.  
  560.     
  561.     def rename(self, fromname, toname):
  562.         '''Rename a file.'''
  563.         resp = self.sendcmd('RNFR ' + fromname)
  564.         if resp[0] != '3':
  565.             raise error_reply, resp
  566.         
  567.         return self.voidcmd('RNTO ' + toname)
  568.  
  569.     
  570.     def delete(self, filename):
  571.         '''Delete a file.'''
  572.         resp = self.sendcmd('DELE ' + filename)
  573.         if resp[:3] in ('250', '200'):
  574.             return resp
  575.         elif resp[:1] == '5':
  576.             raise error_perm, resp
  577.         else:
  578.             raise error_reply, resp
  579.  
  580.     
  581.     def cwd(self, dirname):
  582.         '''Change to a directory.'''
  583.         if dirname == '..':
  584.             
  585.             try:
  586.                 return self.voidcmd('CDUP')
  587.             except error_perm:
  588.                 msg = None
  589.                 if msg.args[0][:3] != '500':
  590.                     raise 
  591.                 
  592.             except:
  593.                 msg.args[0][:3] != '500'
  594.             
  595.  
  596.         None<EXCEPTION MATCH>error_perm
  597.         if dirname == '':
  598.             dirname = '.'
  599.         
  600.         cmd = 'CWD ' + dirname
  601.         return self.voidcmd(cmd)
  602.  
  603.     
  604.     def size(self, filename):
  605.         '''Retrieve the size of a file.'''
  606.         resp = self.sendcmd('SIZE ' + filename)
  607.         if resp[:3] == '213':
  608.             s = resp[3:].strip()
  609.             
  610.             try:
  611.                 return int(s)
  612.             except (OverflowError, ValueError):
  613.                 return long(s)
  614.             except:
  615.                 None<EXCEPTION MATCH>(OverflowError, ValueError)
  616.             
  617.  
  618.         None<EXCEPTION MATCH>(OverflowError, ValueError)
  619.  
  620.     
  621.     def mkd(self, dirname):
  622.         '''Make a directory, return its full pathname.'''
  623.         resp = self.sendcmd('MKD ' + dirname)
  624.         return parse257(resp)
  625.  
  626.     
  627.     def rmd(self, dirname):
  628.         '''Remove a directory.'''
  629.         return self.voidcmd('RMD ' + dirname)
  630.  
  631.     
  632.     def pwd(self):
  633.         '''Return current working directory.'''
  634.         resp = self.sendcmd('PWD')
  635.         return parse257(resp)
  636.  
  637.     
  638.     def quit(self):
  639.         '''Quit, and close the connection.'''
  640.         resp = self.voidcmd('QUIT')
  641.         self.close()
  642.         return resp
  643.  
  644.     
  645.     def close(self):
  646.         '''Close the connection without assuming anything about it.'''
  647.         if self.file:
  648.             self.file.close()
  649.             self.sock.close()
  650.             self.file = None
  651.             self.sock = None
  652.         
  653.  
  654.  
  655. _150_re = None
  656.  
  657. def parse150(resp):
  658.     """Parse the '150' response for a RETR request.
  659.     Returns the expected transfer size or None; size is not guaranteed to
  660.     be present in the 150 message.
  661.     """
  662.     global _150_re
  663.     if resp[:3] != '150':
  664.         raise error_reply, resp
  665.     
  666.     if _150_re is None:
  667.         import re
  668.         _150_re = re.compile('150 .* \\((\\d+) bytes\\)', re.IGNORECASE)
  669.     
  670.     m = _150_re.match(resp)
  671.     if not m:
  672.         return None
  673.     
  674.     s = m.group(1)
  675.     
  676.     try:
  677.         return int(s)
  678.     except (OverflowError, ValueError):
  679.         return long(s)
  680.  
  681.  
  682. _227_re = None
  683.  
  684. def parse227(resp):
  685.     """Parse the '227' response for a PASV request.
  686.     Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)'
  687.     Return ('host.addr.as.numbers', port#) tuple."""
  688.     global _227_re
  689.     if resp[:3] != '227':
  690.         raise error_reply, resp
  691.     
  692.     if _227_re is None:
  693.         import re
  694.         _227_re = re.compile('(\\d+),(\\d+),(\\d+),(\\d+),(\\d+),(\\d+)')
  695.     
  696.     m = _227_re.search(resp)
  697.     if not m:
  698.         raise error_proto, resp
  699.     
  700.     numbers = m.groups()
  701.     host = '.'.join(numbers[:4])
  702.     port = (int(numbers[4]) << 8) + int(numbers[5])
  703.     return (host, port)
  704.  
  705.  
  706. def parse229(resp, peer):
  707.     """Parse the '229' response for a EPSV request.
  708.     Raises error_proto if it does not contain '(|||port|)'
  709.     Return ('host.addr.as.numbers', port#) tuple."""
  710.     if resp[:3] != '229':
  711.         raise error_reply, resp
  712.     
  713.     left = resp.find('(')
  714.     if left < 0:
  715.         raise error_proto, resp
  716.     
  717.     right = resp.find(')', left + 1)
  718.     if right < 0:
  719.         raise error_proto, resp
  720.     
  721.     if resp[left + 1] != resp[right - 1]:
  722.         raise error_proto, resp
  723.     
  724.     parts = resp[left + 1:right].split(resp[left + 1])
  725.     if len(parts) != 5:
  726.         raise error_proto, resp
  727.     
  728.     host = peer[0]
  729.     port = int(parts[3])
  730.     return (host, port)
  731.  
  732.  
  733. def parse257(resp):
  734.     """Parse the '257' response for a MKD or PWD request.
  735.     This is a response to a MKD or PWD request: a directory name.
  736.     Returns the directoryname in the 257 reply."""
  737.     if resp[:3] != '257':
  738.         raise error_reply, resp
  739.     
  740.     if resp[3:5] != ' "':
  741.         return ''
  742.     
  743.     dirname = ''
  744.     i = 5
  745.     n = len(resp)
  746.     while i < n:
  747.         c = resp[i]
  748.         i = i + 1
  749.         if c == '"':
  750.             if i >= n or resp[i] != '"':
  751.                 break
  752.             
  753.             i = i + 1
  754.         
  755.         dirname = dirname + c
  756.     return dirname
  757.  
  758.  
  759. def print_line(line):
  760.     '''Default retrlines callback to print a line.'''
  761.     print line
  762.  
  763.  
  764. def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
  765.     '''Copy file from one FTP-instance to another.'''
  766.     if not targetname:
  767.         targetname = sourcename
  768.     
  769.     type = 'TYPE ' + type
  770.     source.voidcmd(type)
  771.     target.voidcmd(type)
  772.     (sourcehost, sourceport) = parse227(source.sendcmd('PASV'))
  773.     target.sendport(sourcehost, sourceport)
  774.     treply = target.sendcmd('STOR ' + targetname)
  775.     if treply[:3] not in ('125', '150'):
  776.         raise error_proto
  777.     
  778.     sreply = source.sendcmd('RETR ' + sourcename)
  779.     if sreply[:3] not in ('125', '150'):
  780.         raise error_proto
  781.     
  782.     source.voidresp()
  783.     target.voidresp()
  784.  
  785.  
  786. class Netrc:
  787.     """Class to parse & provide access to 'netrc' format files.
  788.  
  789.     See the netrc(4) man page for information on the file format.
  790.  
  791.     WARNING: This class is obsolete -- use module netrc instead.
  792.  
  793.     """
  794.     __defuser = None
  795.     __defpasswd = None
  796.     __defacct = None
  797.     
  798.     def __init__(self, filename = None):
  799.         if filename is None:
  800.             if 'HOME' in os.environ:
  801.                 filename = os.path.join(os.environ['HOME'], '.netrc')
  802.             else:
  803.                 raise IOError, 'specify file to load or set $HOME'
  804.         
  805.         self._Netrc__hosts = { }
  806.         self._Netrc__macros = { }
  807.         fp = open(filename, 'r')
  808.         in_macro = 0
  809.         while None:
  810.             line = fp.readline()
  811.             if not line:
  812.                 break
  813.             
  814.             if in_macro and line.strip():
  815.                 macro_lines.append(line)
  816.                 continue
  817.             elif in_macro:
  818.                 self._Netrc__macros[macro_name] = tuple(macro_lines)
  819.                 in_macro = 0
  820.             
  821.             words = line.split()
  822.             host = None
  823.             user = None
  824.             passwd = None
  825.             acct = None
  826.             default = 0
  827.             i = 0
  828.             while i < len(words):
  829.                 w1 = words[i]
  830.                 if i + 1 < len(words):
  831.                     w2 = words[i + 1]
  832.                 else:
  833.                     w2 = None
  834.                 if w1 == 'default':
  835.                     default = 1
  836.                 elif w1 == 'machine' and w2:
  837.                     host = w2.lower()
  838.                     i = i + 1
  839.                 elif w1 == 'login' and w2:
  840.                     user = w2
  841.                     i = i + 1
  842.                 elif w1 == 'password' and w2:
  843.                     passwd = w2
  844.                     i = i + 1
  845.                 elif w1 == 'account' and w2:
  846.                     acct = w2
  847.                     i = i + 1
  848.                 elif w1 == 'macdef' and w2:
  849.                     macro_name = w2
  850.                     macro_lines = []
  851.                     in_macro = 1
  852.                     break
  853.                 
  854.                 i = i + 1
  855.             if default:
  856.                 if not user:
  857.                     pass
  858.                 self._Netrc__defuser = self._Netrc__defuser
  859.                 if not passwd:
  860.                     pass
  861.                 self._Netrc__defpasswd = self._Netrc__defpasswd
  862.                 if not acct:
  863.                     pass
  864.                 self._Netrc__defacct = self._Netrc__defacct
  865.             
  866.             if host:
  867.                 if host in self._Netrc__hosts:
  868.                     (ouser, opasswd, oacct) = self._Netrc__hosts[host]
  869.                     if not user:
  870.                         pass
  871.                     user = ouser
  872.                     if not passwd:
  873.                         pass
  874.                     passwd = opasswd
  875.                     if not acct:
  876.                         pass
  877.                     acct = oacct
  878.                 
  879.                 self._Netrc__hosts[host] = (user, passwd, acct)
  880.                 continue
  881.             continue
  882.             fp.close()
  883.             return None
  884.  
  885.     
  886.     def get_hosts(self):
  887.         '''Return a list of hosts mentioned in the .netrc file.'''
  888.         return self._Netrc__hosts.keys()
  889.  
  890.     
  891.     def get_account(self, host):
  892.         '''Returns login information for the named host.
  893.  
  894.         The return value is a triple containing userid,
  895.         password, and the accounting field.
  896.  
  897.         '''
  898.         host = host.lower()
  899.         user = None
  900.         passwd = None
  901.         acct = None
  902.         if host in self._Netrc__hosts:
  903.             (user, passwd, acct) = self._Netrc__hosts[host]
  904.         
  905.         if not user:
  906.             pass
  907.         user = self._Netrc__defuser
  908.         if not passwd:
  909.             pass
  910.         passwd = self._Netrc__defpasswd
  911.         if not acct:
  912.             pass
  913.         acct = self._Netrc__defacct
  914.         return (user, passwd, acct)
  915.  
  916.     
  917.     def get_macros(self):
  918.         '''Return a list of all defined macro names.'''
  919.         return self._Netrc__macros.keys()
  920.  
  921.     
  922.     def get_macro(self, macro):
  923.         '''Return a sequence of lines which define a named macro.'''
  924.         return self._Netrc__macros[macro]
  925.  
  926.  
  927.  
  928. def test():
  929.     '''Test program.
  930.     Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...
  931.  
  932.     -d dir
  933.     -l list
  934.     -p password
  935.     '''
  936.     if len(sys.argv) < 2:
  937.         print test.__doc__
  938.         sys.exit(0)
  939.     
  940.     debugging = 0
  941.     rcfile = None
  942.     while sys.argv[1] == '-d':
  943.         debugging = debugging + 1
  944.         del sys.argv[1]
  945.     if sys.argv[1][:2] == '-r':
  946.         rcfile = sys.argv[1][2:]
  947.         del sys.argv[1]
  948.     
  949.     host = sys.argv[1]
  950.     ftp = FTP(host)
  951.     ftp.set_debuglevel(debugging)
  952.     userid = passwd = acct = ''
  953.     
  954.     try:
  955.         netrc = Netrc(rcfile)
  956.     except IOError:
  957.         if rcfile is not None:
  958.             sys.stderr.write('Could not open account file -- using anonymous login.')
  959.         
  960.     except:
  961.         rcfile is not None
  962.  
  963.     
  964.     try:
  965.         (userid, passwd, acct) = netrc.get_account(host)
  966.     except KeyError:
  967.         sys.stderr.write('No account -- using anonymous login.')
  968.  
  969.     ftp.login(userid, passwd, acct)
  970.     for file in sys.argv[2:]:
  971.         if file[:2] == '-l':
  972.             ftp.dir(file[2:])
  973.             continue
  974.         if file[:2] == '-d':
  975.             cmd = 'CWD'
  976.             if file[2:]:
  977.                 cmd = cmd + ' ' + file[2:]
  978.             
  979.             resp = ftp.sendcmd(cmd)
  980.             continue
  981.         if file == '-p':
  982.             ftp.set_pasv(not (ftp.passiveserver))
  983.             continue
  984.         ftp.retrbinary('RETR ' + file, sys.stdout.write, 1024)
  985.     
  986.     ftp.quit()
  987.  
  988. if __name__ == '__main__':
  989.     test()
  990.  
  991.